package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.feign.AliPayFeignApi;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private AliPayFeignApi aliPayFeignApi;      // 注入Feign组件执行远程调用

    @GetMapping("/alipay")
    public Result<String> alipay(String orderNo, int type) {    // String是因为需要返回表单 然后返回浏览器
        // 根据类型判断是在线还是积分支付
        if (StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(type + "")) {
            throw new BusinessException(SeckillCodeMsg.OPERATION_ERROR);
        }
        if (OrderInfo.PAYTYPE_ONLINE.equals(type)) {
            // 在线支付
            String form = orderInfoService.payOnline(orderNo, type);
            return Result.success(form);
        } else if (OrderInfo.PAYTYPE_INTERGRAL.equals(type)) {
            // 积分支付
            orderInfoService.payIntegral(orderNo, type);
        } else {
            throw new BusinessException(SeckillCodeMsg.OPERATION_ERROR);
        }
        return Result.success("");

    }

    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {


//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("同步回调时间为:"+new Date());
        Result<Boolean> result = aliPayFeignApi.verifySign(params);     // 进行验签操作,返回boolean类型
        String orderNo = params.get("out_trade_no");                    // 获取订单编号
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (result != null && !result.hasError()) {

            if(result.getData()) {  // 为true 验签通过
                // 跳转订单详情页面
                response.sendRedirect(frontEndPayUrl+orderNo);
            }else {
//                out.println("验签失败");
                // 跳转到错误页面中
                response.sendRedirect("http://localhost/500.html"); //  模拟跳转一个错误页面
            }
        }
    }

    @RequestMapping("/notify_url")
    public void notifyUrl(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {

        System.out.println("异步回调时间为:"+new Date());
        PrintWriter writer = response.getWriter();
        Result<Boolean> result = aliPayFeignApi.verifySign(params);     // 进行验签操作,返回boolean类型
        //——请在这里编写您的程序（以下代码仅作参考）——
        if (result != null && !result.hasError()) {
            if (result.getData()) { // 为true 验签通过
                // 支付成功业务逻辑
                orderInfoService.paySuccess(params);
                writer.write("success");
            } else {
                writer.write("fail");
            }
        }
    }

    @RequestMapping("/refund")
    public Result<String> refund(String orderNo) {
        // 参数校验
        if (StringUtils.isEmpty(orderNo)) {
            throw new BusinessException(SeckillCodeMsg.OPERATION_ERROR);
        }
        // 根据订单编号查询数据
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (OrderInfo.PAYTYPE_ONLINE.equals(orderInfo.getPayType())) {
            // 在线支付退款流程
            orderInfoService.refundOnline(orderInfo);
        } else if (OrderInfo.PAYTYPE_INTERGRAL.equals(orderInfo.getPayType())) {
            // 积分支付退款流程
            orderInfoService.refundIntegral(orderInfo);
        } else {
            throw new BusinessException(SeckillCodeMsg.OPERATION_ERROR);
        }
        return Result.success("");
    }

}
